﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Word = Microsoft.Office.Interop.Word;
using System.IO;
using System.Linq.Expressions;


public partial class Manage_ListJoined : System.Web.UI.Page
{
    protected PagedDataSource pds = new PagedDataSource();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindData();
        }
    }

    private void BindData()
    {
        CmsDataContext db = new CmsDataContext();
        var q = from aJT in db.JoinTrain
                where aJT.TrainID == Request.Params["tid"]
                select aJT;

        #region 检索条件
        string search = SearchConditionHidden.Value.Trim();
        if (search != "")
        {
            Expression<Func<JoinTrain, bool>> lmbda = PredicateBuilder<JoinTrain>.CreatePredicate(new string[] { "Name", "Country", "Village", "Street", "Phone", "Memo" }, search, "aJT");
            q = q.Where(lmbda);
        }
        #endregion

        var p = q.Select(aJT => new
                {
                    ID = aJT.ID,
                    Name = aJT.Name,
                    Age = aJT.Age,
                    Country = aJT.Country,
                    Street = aJT.Street,
                    Village = aJT.Village,
                    Memo = aJT.Memo,
                    Phone = aJT.Phone
                });

        pds = new PagedDataSource();
        pds.AllowPaging = true;
        pds.PageSize = Toolkit.PageSize;
        pds.DataSource = p.ToList();


        #region 获取当前要显示的页
        int pageIndex = 0;
        pageIndex = Convert.ToInt32(CurrentPage.Value) - 1;
        if (pageIndex >= pds.PageCount)
        {
            pageIndex = pds.PageCount - 1;
        }
        if (pageIndex <= 0)
        {
            pageIndex = 0;
        }
        #endregion

        pds.CurrentPageIndex = pageIndex;

        TopicsView.DataSource = pds;
        TopicsView.DataBind();

        CurrentPage.Value = Convert.ToString(pageIndex + 1);
        SearchCondition.Text = SearchConditionHidden.Value.Trim();
    }

    protected void ChangePage(object sender, CommandEventArgs e)
    {
        string kind = Convert.ToString(e.CommandArgument);
        int p = Convert.ToInt32(CurrentPage.Value);

        if (kind == "F")
        {
            CurrentPage.Value = "1";
        }
        else if (kind == "P")
        {
            p--;
            CurrentPage.Value = Convert.ToString(p);
        }
        else if (kind == "N")
        {
            p++;
            CurrentPage.Value = Convert.ToString(p);
        }
        else if (kind == "L")
        {
            CurrentPage.Value = Convert.ToString(Int32.MaxValue);
        }
        else if (kind == "G")
        {
            TextBox gtp;
            foreach (Control c in TopicsView.Controls)
            {
                gtp = c.FindControl("GotoPage") as TextBox;
                if (gtp != null)
                {
                    try
                    {
                        CurrentPage.Value = Convert.ToString(Convert.ToInt32(gtp.Text.Trim()));
                    }
                    catch
                    {
                        //CurrentPage.Value = "1";
                    }

                    break;
                }
            }
        }

        BindData();
    }

    protected void Search_Click(object sender, EventArgs e)
    {
        SearchConditionHidden.Value = SearchCondition.Text.Trim();
        BindData();
    }
    protected void Export_Click(object sender, EventArgs e)
    {
        Word.Application app = null;
        Word.Document doc = null;

        object ms = Type.Missing;

        try
        {
            CmsDataContext db = new CmsDataContext();
            Train train = (from aT in db.Train
                           where aT.ID == Request.Params["tid"]
                           select aT).First();

            var joined = from aJT in db.JoinTrain
                         where aJT.TrainID == Request.Params["tid"]
                         orderby aJT.Name
                         select aJT;


            string path = Server.MapPath("~/Temps");
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }

            string file = Toolkit.NextUUID + ".doc";
            File.Copy(Server.MapPath(Toolkit.PathOfExportJoined), string.Format("{0}/{1}", path, file));

            app = new Word.Application();
            doc = app.Documents.Open(string.Format("{0}/{1}", path, file));

            Word.Bookmark bm = doc.Bookmarks["TrainName"];
            bm.Range.Text = train.Name;

            bm = doc.Bookmarks["TrainTime"];
            bm.Range.Text = string.Format("{0:yyyy年MM月dd日 HH:mm}", train.Started);

            bm = doc.Bookmarks["Printer"];
            bm.Range.Text = Toolkit.CurrentUserName;

            bm = doc.Bookmarks["Printed"];
            bm.Range.Text = string.Format("{0:yyyy年MM月dd日 HH:mm}", DateTime.Now);

            Word.Row row;
            Word.Cell cell;
            Word.Table tbl = doc.Tables[1];

            int iRow = 0;
            foreach (var jt in joined)
            {
                iRow++;
                row = tbl.Rows.Add();

                cell = row.Cells[1];
                cell.Range.Text = Convert.ToString(iRow);
                cell.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                cell = row.Cells[2];
                cell.Range.Text = jt.Name;
                cell.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                cell = row.Cells[3];
                cell.Range.Text = jt.Phone;
                cell.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                cell = row.Cells[4];
                cell.Range.Text = string.Format("{0} - {1} - {2}", jt.Country, jt.Street, jt.Village);
                cell.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;

                cell = row.Cells[5];
                cell.Range.Text = jt.Memo;
                cell.VerticalAlignment = Word.WdCellVerticalAlignment.wdCellAlignVerticalCenter;
            }

            doc.Save();
            doc.Close(ref ms, ref ms, ref ms);

            doc = null;

            Response.Redirect(string.Format("~/Temps/{0}", file));
        }
        catch (Exception ee)
        {
        }
        finally
        {
            if (app != null)
            {
                app.Quit(ref ms, ref ms, ref ms);
                app = null;
            }
        }
    }
}